import Vue from 'vue'
import VueRouter from 'vue-router'
// 目标:通过路由实现登录注册组件的切换
// 1.1 创建两个组件:views/Login/Login.vue views/Reg/Reg.vue
// 1.2 在router/index.js中进行路由配置
// 1.3 在App.vue中使用router-view组件占位

// 在js代码中写的@符号都会被解析成src的绝对路径
import store from '@/store'

const Login = () => import('@/views/Login/Login.vue')

const Reg = () => import('@/views/Reg/Reg.vue')

const Main = () => import('@/views/Main/Main.vue')

const Home = () => import('@/views/Menu/Home/Home.vue')

const UserInfo = () => import('@/views/Menu/User/UserInfo.vue')

const UserAvatar = () => import('@/views/Menu/User/UserAvatar.vue')

const UserPwd = () => import('@/views/Menu/User/UserPwd.vue')

const ArtCate = () => import('@/views/Menu/Article/ArtCate.vue')

const ArtList = () => import('@/views/Menu/Article/ArtList.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

const routes = [
  // 一个对象表示一条路由规则
  // { path: '/', redirect: '/login' },
  { path: '/login', name: 'Login', component: Login },
  { path: '/reg', name: 'Reg', component: Reg },
  {
    path: '/',
    name: 'Main',
    component: Main,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: Home
      },
      {
        path: 'user-info',
        name: 'UserInfo',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        name: 'UserAvatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        name: 'UserPwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        name: 'ArtCate',
        component: ArtCate
      },
      {
        path: 'art-list',
        name: 'ArtList',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由全局前置导航守卫:路由切换是进行拦截
// 参数1:到哪去
// 参数2:从哪来
// 参数3:是否放行,直接调用表示放行,调用传入false 表示拦截不放行,调用传入path表示强制导航到指定路径
// includes() 判断元素是否在数组内,仅支持基本数据类型
router.beforeEach((to, from, next) => {
  const whiteList = ['/login', '/reg']
  // 如果用户没有token却访问了/home,这个判断就失效了
  // 逆向思维:不是访问/login和/reg时 并且没有token就让他去login
  if (!whiteList.includes(to.path) && !store.state.token) {
    Vue.prototype.$message.error('请您先登录!')
    return next('/login')
  }
  next()
})

export default router
